import {ChatMessage, Msg_Type, MsgEvent} from "./message.ts";
import type {GroupItem} from "./chat_model.ts";
import {Chatting, ContactsItem} from "./chat_model.ts";

async function confirmSent(msgEvent: MsgEvent, chatStore: any) {
    console.log(`消息发送成功回调. Msg：localId=${msgEvent.localId}, msgId=${msgEvent.msgId}`)

    let chatting = chatStore.getChattingByRelId(msgEvent.chatId!,msgEvent.isGroup!);
    if (!chatting) {
        console.error("getChatting不能为Null,代码逻辑错误...");
        return;
    }
    //为message赋值ID
    let message = chatting.messages.find((e: ChatMessage) =>
        String(e.localId) === String(msgEvent.localId)
    )
    if (message) {
        message.id = msgEvent.msgId;
    }
}

async function showRead(msgId: string, chatId: string) {
    console.log(`消息已读 msgId=${msgId}, chatId = ${chatId}`)
}

async function showRecall(msgId: string, chatId: string) {
    console.log(`已撤回消息 msgId=${msgId}, chatId = ${chatId}`)
}

/**
 * 展示对方发送的消息+自己发送的消息
 * @param msg
 * @param chatter
 * @param chatStore
 */
async function showChatMsg(msg: ChatMessage, chatter: ContactsItem | GroupItem, chatStore: any) {
    if (!msg.chatId) {
        console.warn("show ChatMsg时，chatId没有值");
        return;
    }

    if (!chatter) {
        console.error("获取不到chatter, 无法创建chatting对象")
        return;
    }

    console.log("showChatMsg... chatter = ", chatter);
    let chatting = chatStore.getChattingByRelId(msg.chatId,msg.isGroup);
    //如果没有，则创建chatting
    if (!chatting) {
        console.log("getChatting为Null,即将创建chatting...")
        chatting = chatStore.obtainChatting(chatter);
        console.log("new chatting = ", chatting)

    }

    //填充消息的字段：头像等
    setOwnerField(msg, chatting, chatter);

    markLastSign(chatting, msg);
    // console.debug("展示的消息[msg] = " + JSON.stringify(msg));

    if (!chatting.messages) {
        chatting.messages = [];
    }
    chatting.messages.push(msg)
}

/**
 * 填充消息发送者的showName、avatarUrl等字段
 * @param msg
 * @param chatting
 * @param chatter
 */
function setOwnerField(msg:ChatMessage, chatting:Chatting, chatter:GroupItem | ContactsItem){
    //如果消息是自己的，直接取自己的头像
    if (msg.isSelf) {
        msg.avatarUrl = chatting.user?.avatarUrl
    } else {
        //取聊天人的头像。如果是群消息，则头像和昵称取群成员里面的
        if (chatting.isGroup) {
            let member = (chatter as GroupItem).users.find(m => {
                return String(m.userId) === String(msg.sender)
            })
            msg.showName = (member?.aliasName) ? (member?.aliasName) : (member?.nickname)
            msg.avatarUrl = (member?.avatarUrl)
        } else {
            let member = (chatter as ContactsItem);
            msg.avatarUrl = (member?.avatarUrl)
        }
    }
}

function markLastSign(chatting: Chatting, message: ChatMessage) {
    if (!message.isSelf) {
        chatting.unreadCount++;
    }
    chatting.lastTime = new Date().toLocaleString();

    //消息类型：0文本、1图片、2视频、3语音、4文件
    switch (message.type) {
        case Msg_Type.TEXT:
            chatting.lastTip = message.content
            break;
        case Msg_Type.PICTURE:
            chatting.lastTip = "[图片]"
            break;
        case Msg_Type.VIDEO:
            chatting.lastTip = "[视频]"
            break;
        case Msg_Type.VOICE:
            chatting.lastTip = "[语音]"
            break;
        case Msg_Type.FILE:
            chatting.lastTip = "[文件]"
            break;
        default:
            chatting.lastTip = "[...]";
    }
}

export {
    confirmSent,
    showRead,
    showRecall,
    showChatMsg,
    setOwnerField,
}